import cv2
image = cv2.imread('hat.png', cv2.IMREAD_GRAYSCALE)
cv2.imshow("Input", image)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
image_opened = cv2.dilate(image, kernel)
image_opened = cv2.erode(image_opened, kernel)
image_closed = cv2.erode(image_opened, kernel)
image_closed = cv2.dilate(image_closed, kernel)
cv2.imshow("Output", image_closed)
cv2.waitKey()
cv2.destroyAllWindows()